<template>
    <div class="case">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-copy"></i> 新增配置</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-form ref="form" :model="form" :rules="rules">
            <el-tabs v-model="message">
                <!-- 配置信息 -->
                <el-tab-pane :label="`配置信息`" name="first">
                    <el-form-item label="配置名称" prop="name">
                        <el-input v-model="form.name" style="width:500px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属项目" prop="project_id">
                        <el-select v-model="form.project_id" placeholder="选择项目" style="width:500px;">
                            <el-option v-for="project in projects"
                                :key="project.id"
                                :label="project.name"
                                :value="project.id"
                                >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('apiHeaders')">添加Headers</el-button>
                        <base-extract-table :tableData="form.apiHeaders" @removeRowByIndex="removeHeadersByIndex"></base-extract-table>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('variables')">添加全局变量(variables)</el-button>
                        <base-extract-table :tableData="form.variables" @removeRowByIndex="removeVariablesByIndex"></base-extract-table>
                    </el-form-item>
                </el-tab-pane>
            </el-tabs>
                <el-form-item style="margin-top: 50px">
                    <el-button type="primary" @click="save('form')">保存</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    import baseExtractTable from '../SmallParts/baseExtractTable'
    import {removeInArrayByIndex} from '../../utils/common'
    import { projects_names, edit_configures, read_configure } from '../../api/api';
    
    export default {
        name: 'case',
        components: { baseExtractTable },
        data() {
            return {
                message: 'first',
                projects: [],
                rules: {
                    name: [
                        { required: true, message: '请配置名称', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ],
                    project_id: [
                        { required: true, message: '请选择所属项目', trigger: 'change' }
                    ],
                },
                form: {
                    name: '',
                    project_id:'',
                    // 格式为: [{"keyName":"", "value":""}, { , }...]w
                    apiHeaders:[],
                    variables: [],
                }
            }
        },
        created() {
            this.getData();
            this.getProjects();
        },
        methods: {
            // 获取指定要修改配置的数据
            getData(){
                read_configure(this.$route.query.id)
                    .then(response => {
                        this.form.name = response.data.configure_name
                        this.form.project_id = response.data.project_id
                        this.form.apiHeaders = response.data.header
                        this.form.variables = response.data.variables
                    })
            },

            // 获取项目列表
            getProjects() {
                projects_names()
                    .then(response => {
                        this.projects = response.data;
                    })
                    .catch(error =>{
                        this.$message.error('获取项目列表失败');
                    });
            },

            // 保存配置
            save: function(formData){
                this.$refs[formData].validate((valid) => {
                    if (valid) {
                        //需要格式转换
                        let postForm = this.formTransform();
                        edit_configures(this.$route.query.id, postForm)
                            .then(response => {
                                const code = response.data.code;
                                this.$message.success('配置修改成功');
                                this.$router.push({
                                    path: '/ConfiguresList',
                                })
                            })
                            .catch(error =>{
                                this.$message.error('配置修改失败');
                            })
                        ;
                    } else {
                        window.console.log('表单格式校验失败!');
                        this.$message.error('请输入必填项');
                        return false;
                    }
                });
            },

            addTableRow(name){
                if(name === "apiHeaders"){
                    this.form.apiHeaders.push({});
                }
                else if (name === "variables"){
                    this.form.variables.push({});
                }
                else {
                    window.console.log("无法识别: " + name);
                }
            },
            // 移除headers单行
            removeHeadersByIndex(array, removeIndex){
                this.form.apiHeaders = removeInArrayByIndex(array, removeIndex);
            },
            // 移除variables单行
            removeVariablesByIndex(array, removeIndex){
                this.form.variables = removeInArrayByIndex(array, removeIndex);
            },
            // 发送请求前的格式转换
            formTransform: function () {
                //深拷贝
                let postForm = JSON.parse(JSON.stringify(this.form));
                let configuredata = {}
                configuredata["name"] = postForm.name;
                configuredata["project_id"] = postForm.project_id;
                configuredata["author"] = "刘翔";
                configuredata["request"] = {};
                configuredata["request"]['config'] = {}
                configuredata["request"]['config']["request"] = {}
                if (postForm.apiHeaders.length != 0){
                    let headers = {};
                    for (let i =0; i < postForm.apiHeaders.length; i++) {
                        headers[postForm.apiHeaders[i].keyName] = postForm.apiHeaders[i].value
                    };
                    configuredata["request"]["config"]["request"]["headers"] = headers
                }
                if (postForm.variables.length != 0){
                    let variables = {};
                    for (let i =0; i < postForm.variables.length; i++) {
                        variables[postForm.variables[i].keyName] = postForm.variables[i].value
                    };
                    configuredata["request"]["config"]["variables"]= variables
                }

                configuredata["request"] = JSON.stringify(configuredata["request"])
                return configuredata
            }
        },
        computed: {}
    }

</script>

<style>

.container {
    text-align: left;
    padding: 10px;
}
el-form-item{
    margin-top: 20px;
}

</style>

